/**
 * 根据client类型创建实例
 * @param clientType client类型
 * @returns
 */
// export function useClient<TClient>(
//   clientType: new (baseUrl?: string, http?: FetchClient) => TClient,
// ): TClient {
//   const { baseUrl, http } = useApiConfig();

import axios, { AxiosInstance } from 'axios';
import { ApiException, HttpValidationProblemDetails, ProblemDetails } from './client';
import { SolidSwal2, SolidSwal2Toast } from '~/components/SolidSwal2';
import { SolidSweetAlertOptions } from 'sweetalert2-solid-content';

//   return new clientType(baseUrl, http);
// }

export const DefaultAxiosInstance = axios.create({});

export const useClient = <TClient extends {}>(clientType: new (baseUrl?: string, instance?: AxiosInstance) => TClient, baseUrl?: string, instance?: AxiosInstance): TClient => {
  return new clientType(baseUrl ?? '', instance ?? DefaultAxiosInstance);
};

export type MaybeException = ApiException | ProblemDetails | HttpValidationProblemDetails;

export const handleException = (error: MaybeException, alertOptions?: Partial<SolidSweetAlertOptions>) => {
  if (axios.isCancel(error)) {
    return SolidSwal2Toast.fire({ icon: 'info', title: '操作取消' });
  }

  if (ApiException.isApiException(error)) {
    // api exception
    return SolidSwal2Toast.fire({
      icon: 'error',
      title: `[${error.status}] ${error.message}`,
      ...(alertOptions as any),
    });
  }

  if (error['errors']) {
    // client-side error
    return SolidSwal2.fire({
      icon: 'error',
      title: '参数校验错误',
      html: error.errors,
      ...(alertOptions as any),
    });
  }

  // server-side error
  return SolidSwal2.fire({
    icon: 'error',
    title: error.title ?? '未知错误',
    html: error.detail,
    ...(alertOptions as any),
  });
};

export const autoAlert = handleException;

const parseErrorTitle = (error: MaybeException) => {
  if (ApiException.isApiException(error)) {
    return `[${error.status}] ${error.message}`;
  }

  if (error['errors']) {
    return '参数校验错误';
  }

  return error.title ?? '未知错误';
};

const parseErrorHtml = (error: MaybeException) => {
  if (ApiException.isApiException(error)) {
    return undefined;
  }

  if (error['errors']) {
    return error.errors;
  }

  return error.detail;
};

export const toastOnly = (error: MaybeException, alertOptions?: Partial<SolidSweetAlertOptions>) => {
  return SolidSwal2Toast.fire({
    icon: 'error',
    title: parseErrorTitle(error),
    ...(alertOptions as any),
  });
};

